<template>
  <div class="app-container" v-loading="pageLoading">
    <el-row :gutter="10">
      <el-col :span="12">
        <div class="panel-info">
          <div class="panel-title">文件列表</div>
          <div class="panel-body">
            <el-button v-if="basicInfoShow" type="primary" class="fr" @click="createItems"
              v-permission="'fileManage.add'">创建
            </el-button>
            <div v-if="basicInfoShow" class="filter-container">
              <el-input style="width: 260px;" placeholder="输入备件/编码按回车" clearable class="filter-item"
                @keyup.enter.native="research" @clear="research" v-model="query.file_code">
              </el-input>
              <el-button class="filter-item" type="success" plain @click="research">查询</el-button>
              <el-button class="filter-item" type="info" plain @click="exportData" :loading="exportLoading">导出
              </el-button>

            </div>
            <z-table :list="list" :tableProps="tableProps" :columns="columns" @editItem="editItem"
              @deleteItem="deleteItem" @row-click="rowClick">
            </z-table>
            <z-pagination :pagination="pagination" :total="total" :page.sync="query.page" :limit.sync="query.size"
              @change="getList"></z-pagination>
            <z-form-dialog :name="name" :data="data" :formProps="formProps" :fields="fields" @submit="submit"
              :submitLoading="submitLoading" :visible.sync="editFormVisible"></z-form-dialog>
          </div>
        </div>
      </el-col>
      <el-col :span="12">
        <div class="panel-info">
          <div class="panel-title">设备列表</div>
          <div class="panel-body" v-if="deviceShow">
            <el-button class="fr" size="mini" type="primary" icon="el-icon-plus" circle plain @click="addDevice">
            </el-button>
            <div class="filter-container">
            </div>
            <z-table :list="deviceList" :tableProps="tableProps" :columns="deviceColumns" @editItem="editItem"
              @deleteItem="deleteItem">
              <template v-slot:content="v">
                <span v-if="v.key == 'machine_status'" class="text-label"
                  :style="{background:v.row[v.key]==1?'#67c23a':v.row[v.key]==4?'#e6a23c':'f56c6c'}">
                  {{getMatchingData(v.row[v.key],'machine_status')}}
                </span>
                <span v-else>{{ v.row[v.key] }}</span>
              </template>
              <template v-slot:operation='v'>
                <a style="margin-left:5px;" href="javascript:;" class="text-red"
                  @click.stop="deleteDetail(v.row)">删除</a>
              </template>
            </z-table>
            <z-pagination :pagination="pagination" :total="deviceTotal" :page.sync="deviceQuery.page"
              :limit.sync="deviceQuery.size" @change="getdevicelist"></z-pagination>
          </div>
        </div>
      </el-col>
    </el-row>
    <!-- 添加设备组件 -->
    <add-device :addDeviceShow="addDeviceShow" :deviceIDData='deviceIDData' @addDevices='addDevices' />
  </div>
</template>

<script>
import commonMixin from '@/views/_common/mixin'
import AddDevice from '@/views/tpm/components/addDevice.vue'
export default {
  name: 'fileManage',
  mixins: [commonMixin],
  components: { AddDevice },
  props: {
    basicInfoShow: {
      type: Boolean,
      default: true,
    },
    deviceId: {
      type: String,
      default: '',
    },
  },
  data() {
    return {
      query: {
        file_code: '',
        page: 1,
        size: 10,
      },
      name: '文件信息',
      api: this.$api.TpmEquipmentFile,
      baseUrl: this.$api.baseUrl,
      postForList: true,
      tableProps: {
        border: true,
        opsColWith: 100,
        fixed: false,
        highlightCurrentRow: true,
        hideOperations: false,
      },
      columns: [
        { title: '文件编号', key: 'file_code' },
        { title: '文件名称', key: 'file_name' },
        { title: '修改人', key: 'modify_user', width: 100 },
        { title: '最后修改时间', key: 'modify_time', width: 100 },
      ],

      fields: [
        { title: '文件编号', key: 'file_code', span: 12, required: true },
        { title: '文件名称', key: 'file_name', span: 12, required: true },
        {
          title: '上传附件',
          key: 'file_list',
          span: 24,
          name: 'fileUploader',
          tips: '不能大于20M',
          props: {
            action: '',

            // accept: '.jpg,.png,.pdf,',
            limit: 1,
            autoUpload: false,
            multiple: true,
            'on-change': this.uploadOnchange,
            'before-remove': this.beforeRemove,
            'on-preview': this.onPreview,
            'on-exceed': this.handleExceed,
          },
        },
      ],
      // 上传数据
      formData: new FormData(),
      deleteArray: [],
      // 设备状态
      deviceStatus: [
        {
          value: 1,
          label: '正常',
        },
        {
          value: 4,
          label: '停用',
        },
        {
          value: 5,
          label: '报废',
        },
      ],
      // 设备列表
      deviceColumns: [
        { title: '设备类型', key: 'machine_type_name', width: 100 },
        { title: '设备编号', key: 'machine_code', width: 100 },
        { title: '设备名称', key: 'machine_name', width: 100 },
        { title: '设备规格型号', key: 'machine_description', width: 100 },
        { title: '设备出厂编号', key: 'factory_number', width: 140 },
        { title: '制造商', key: 'manufacturer', minWidth: 80 },
        { title: '供应商', key: 'vendor_name', width: 80 },
        { title: '设备状态', key: 'machine_status', width: 100 },

        { title: '签收人', key: 'signed_by', width: 80 },
        { title: '签收日期', key: 'signed_date', width: 100 },
        { title: '管理人', key: 'custodian', width: 80 },
        { title: '登记日期', key: 'register_date', width: 100 },
        { title: '所属工厂', key: 'plant_name', width: 100 },
        { title: '所属线体', key: 'line_name', width: 100 },
        { title: '修改人', key: 'modify_user', width: 100 },
        { title: '最后修改时间', key: 'modify_time', width: 100 },
      ],
      addDeviceShow: false,
      deviceShow: false,
      deviceTotal: 0,
      deviceQuery: {
        page: 1,
        size: 10,
      },
      deviceList: [],
      fileId: '',
      deviceIDData: [],
    }
  },
  computed: {},
  watch: {
    basicInfoShow: {
      immediate: true,
      handler(val, old) {
        if (!val) {
          this.tableProps = {
            border: true,
            opsColWith: 160,
            fixed: false,
            highlightCurrentRow: true,
            hideOperations: true,
          }
          this.query.machine_id = this.deviceId
        }
      },
    },
  },
  created() {
    this.research()
  },
  mounted() {},
  methods: {
    // 添加设备
    addDevice() {
      this.addDeviceShow = true
      this.deviceIDData = []
      this.deviceList.forEach((i) => {
        this.deviceIDData.push(i.id)
      })
    },
    addDevices(val) {
      let data = {
        equipment_file_id: this.fileId,
        machine_ids: val,
      }
      this.$request(this.api + 'SaveDetail', data, 'post').then((r) => {
        this.$message.success('设备添加成功')
        this.addDeviceShow = false
        this.getdevicelist()
      })
    },
    deleteDetail(val) {
      this.$confirm('确定要删除这条记录？').then(() => {
        this.pageLoading = true
        this.$request(this.api + 'DeleteDetail' + '/' + val.file_machine_id, {}, 'post')
          .then((r) => {
            this.$message.success('操作成功')
            this.getdevicelist()
          })
          .finally(() => {
            this.pageLoading = false
          })
      })
    },
    getMatchingData(val, code) {
      if (code == 'machine_status') {
        let tmp = this.deviceStatus.find((i) => i.value == val)
        return tmp ? tmp.label : ''
      }
    },
    // 点击文件列表
    rowClick(row) {
      this.deviceShow = true
      this.fileId = row.id
      this.getdevicelist()
    },
    getdevicelist() {
      let data = {
        page: this.deviceQuery.page,
        size: this.deviceQuery.size,
        equipment_file_id: this.fileId,
      }
      this.$request(this.api + 'GetDetailList', data, 'post').then((r) => {
        const { total, list } = r
        this.deviceTotal = total
        this.deviceList = list
      })
    },
    // 创建数据
    createItems() {
      this.formData = new FormData()
      this.deleteArray = []
      this.createItem()
    },
    // 提交文件
    submit() {
      this.data.deleteArray = this.deleteArray
      this.formData.append('model', JSON.stringify(this.data))
      this.submitLoading = true
      this.$request(this.baseUrl + 'Tpm/TpmEquipmentFile/add', this.formData, 'post')
        .then((r) => {
          this.$message.success('操作成功')
          this.editFormVisible = false
          this.deleteArray = []
          this.getList()
        })
        .finally(() => {
          this.submitLoading = false
        })
    },
    // 上传
    uploadOnchange(file, fileList) {
      let f = file.raw
      const isLt20M = f.size / 1024 / 1024 < 20
      if (!isLt20M) {
        fileList.splice(fileList.indexOf(f), 1)
        return this.$message.error('上传档案大小不能超过 20MB!')
      }
      this.formData.append('files', f)
    },
    // 清除附件
    beforeRemove(file, fileList) {
      return this.$confirm(`确定要删除${file.name}?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        if (file.FileId) {
          // 已经有附件了,进行删除
          this.deleteArray.push(file.FileId)
        } else {
          this.formData = new FormData()
          // 刚上传没有点确定
          fileList.forEach((i) => {
            if (!i.FileId && i.name != file.name) {
              this.formData.append('file', i.raw)
            }
          })
        }
      })
    },
    // 预览
    onPreview(file) {
      this.filedownload(this.baseUrl, file)
    },
    filedownload(host, file) {
      host = host.replace('api/', '')
      let a = document.createElement('a')
      a.setAttribute('href', this.fileUrl(host, file.file_path))
      a.setAttribute('target', '_blank')
      a.setAttribute('download', file.name)

      a.click()
      a.remove()
    },
    fileUrl(host, file) {
      host = host.replace('api/', '')
      return host + file
    },

    // 超过最大上传数
    handleExceed() {
      return this.$message.warning('最多只能上传1个附件')
    },
  },
}
</script>

<style lang="scss" scoped></style>